package com.service.socket.protocol;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.service.bean.data.Data;
import com.service.bean.data.Data_1_x;
import com.service.bean.data.Data_2_x;
import com.service.other.Logger;

public class DataProtocol {
	
	private static String protocol = "(?<year>\\w{2})(?<month>\\w{2})(?<day>\\w{2})(?<hour>\\w{2})(?<minute>\\w{2})(?<second>\\w{2})(?<latitude>\\w{8})(?<longitude>\\w{8})(?<speed>\\w{2})(?<direction>\\w{4})(?<mileage>\\w{4})(?<mileage2>\\w{4})(?<speed2>\\w{2})(?<rawStatus>\\w{8})(?<vehicleType>\\w{2})(?<oilInt>\\w{2})(?<motorSpeed>\\w{4})(?<auxiMotorSpeed>\\w{4})(?<sweepSpeed>\\w{4})(?<odorValue>\\w{2})(?<oilDec>\\w{2})(?<recoWeight>\\w{4})(?<unrecoWeight>\\w{4})(?<sweepSpeed2>\\w{4})(?<oilVoltage>\\w{2})(?<oilSerial>\\w{2})(?<altitude>\\w{4})(?<rawSwitch>\\w{8})(?<rawFault>\\w{8})(?<rawOutput>\\w{2})";
	
	private static String regexF057 = "(?<fileName>\\w*)(?<size>\\w{4})(?<index>\\w{8})(?<checksum>\\w{2})";
	
	public static Data Parser(String rawData,String version) {
		Data data = null;
		if("1".equals(version)){
			data = new Data_1_x();
		}else{
			data = new Data_2_x();
		}
		try{
			Pattern p = Pattern.compile(protocol);
			Matcher m = p.matcher(rawData);
			if (m.find()) {
				Field[] fields = data.getClass().getFields();
				//this.getClass().getDeclaredFields();全部字段
				//this.getClass().getFields();public字段
				for (int i = 0; i < fields.length; i++) {
					fields[i].setAccessible(true);
					String name = fields[i].getName();
					try {
						fields[i].set(data, Conversion.reversal(m.group(name)));
					} catch (Exception e) {
						Logger.err(e);
					}
				}
			}
		}catch(Exception e){
			Logger.err(e);
		}
		return data;
	}
	public static List<String> parseF057(String dataArea){
		List<String> list = null;
		try{
			list = new ArrayList<String>();
			Pattern p = Pattern.compile(regexF057);
			Matcher m = p.matcher(dataArea);
			if(m.find()) {
				int i = 1;
				while(i <= m.groupCount()){
					list.add(m.group(i));
					i++;
				}
			}
		}catch(Exception e){
			Logger.err(e);
		}
		return list;
	}
}
